package net.topcrazy.base.db.dao;

/**
 * 数据库访问对象层基类（Ajax）
 * 
 * <pre>
 * 本类提供一些共用的Ajax分页访问方法，主要包含：
 *   1、Ajax 生成分页链接字符串
 * </pre>
 * 
 * @author AllenZhang
 * @version 0.3 (2009.07.29)
 * @modify AllenZhang (2009.07.29)
 */
public class BasePageDAO extends BaseDAO {

	/**
	 * 通过将普通的select语句转换select count(1) ...语句后查询出记录总数
	 * 
	 * @param selectSql
	 *            查询SQL语句
	 * @param params
	 *            参数数组，用于传递参数值，如果不必传递参数，则此参数可赋予null值
	 * @return 结果数量
	 * @author AllenZhang
	 */
	protected int findTotalWithParams(String selectSql, Object[] params)
			throws Exception {
		this.getDbTemplate().testStringIsNullOrBlank(selectSql);
		return this.getDbTemplate().findForInteger(
				" select count(1) from ( " + selectSql + " ) ", params);
	}

	/**
	 * Ajax 生成分页链接字符串
	 * 
	 * @param recordTotal
	 *            总记录数
	 * @param pageObj
	 *            PageBaseAction 类或子类
	 * @return 分页链接字符串
	 * @author AllenZhang
	 */
	/*
	 * protected String pageLinkString(int recordTotal, UIPageObj pageObj)
	 * throws Exception { return this.pageLinkString(recordTotal,
	 * pageObj.getPageCount(), pageObj.getPageIndex(),
	 * pageObj.getDoSearchFunctionName()); }
	 */

	/**
	 * Ajax 生成分页链接字符串
	 * 
	 * @param recordTotal
	 *            总记录数
	 * @param recordTotalAPage
	 *            每页记录数
	 * @param pageIndex
	 *            第几页
	 * @param doSearchFunctionName
	 *            执行搜索的JS函数名称
	 * @param params
	 *            参数数组，用于传递参数值
	 * @param url
	 *            需要分页的地址
	 * @return 分页链接字符串
	 * @author AllenZhang
	 */
	private synchronized String pageLinkString(int recordTotal,
			int recordTotalAPage, int pageIndex, String doSearchFunctionName)
			throws Exception {
		String space = "&nbsp;&nbsp;";
		if (doSearchFunctionName == null) {
			doSearchFunctionName = "framework_doSearch";
		} else if ("".equals(doSearchFunctionName.trim())) {
			doSearchFunctionName = "framework_doSearch";
		}
		if (recordTotal > 0 && recordTotalAPage > 0 && pageIndex > 0) {
			int pages = recordTotal / recordTotalAPage;
			if ((recordTotal % recordTotalAPage) > 0) {
				pages++;
			}
			int prior = pageIndex - 1;
			if (prior <= 0) {
				prior = 1;
			}

			int next = pageIndex + 1;
			if (next >= pages) {
				next = pages;
			}
			if (pages > 1) {
				String reStr = createBoundForCutPage(pageIndex, 10, pages);
				int lowerLimit = Integer.valueOf(reStr.substring(0, reStr
						.indexOf("_")));
				int upperLimit = Integer.valueOf(reStr.substring(reStr
						.indexOf("_") + 1, reStr.length()));
				String pageHTML = "";
				for (int i = lowerLimit; i <= upperLimit; i++) {
					if (pageIndex != i) {
						pageHTML += "<a href='javascript:"
								+ doSearchFunctionName + "(" + i + ");'>[" + i
								+ "]</a>" + "&nbsp;";
					} else {
						pageHTML += i + "&nbsp;&nbsp;";
					}
				}

				StringBuffer pageStr = new StringBuffer();
				pageStr.append("第&nbsp;" + pageIndex
						+ "&nbsp;&nbsp;页&nbsp;/&nbsp;&nbsp;共&nbsp;" + pages
						+ "&nbsp;&nbsp;页&nbsp;/&nbsp;&nbsp;共&nbsp;"
						+ recordTotal + "&nbsp;&nbsp;条记录");
				pageStr.append(space);

				if (pageIndex > 1) {
					pageStr
							.append("<a href='javascript:void(0);' onclick='javascript:"
									+ doSearchFunctionName + "(1);'>首页</a>");
				} else {
					pageStr.append("首页");
				}
				pageStr.append(space);

				if (pageIndex > 1) {
					pageStr
							.append("<a href='javascript:void(0);' onclick='javascript:"
									+ doSearchFunctionName
									+ "("
									+ prior
									+ ");'>前页</a>");
				} else {
					pageStr.append("前页");
				}
				pageStr.append(space);

				if (!"".equals(pageHTML)) {
					pageStr.append(pageHTML);
					pageStr.append(space);
				}

				if (pageIndex < pages) {
					pageStr
							.append("<a href='javascript:void(0);' onclick='javascript:"
									+ doSearchFunctionName
									+ "("
									+ next
									+ ");'>后页</a>");
				} else {
					pageStr.append("后页");
				}
				pageStr.append(space);

				if (pageIndex < pages) {
					pageStr
							.append("<a href='javascript:void(0);' onclick='javascript:"
									+ doSearchFunctionName
									+ "("
									+ pages
									+ ");'>末页</a>");
				} else {
					pageStr.append("末页");
				}

				pageStr.append(space);

				String gotoPage = "跳转到，第 <input type='text' id='pageIndexForcreatePage' name='pageIndexForcreatePage' style='width:30px;height:14px;text-align:center;font-size:12px;' value='"
						+ next
						+ "' onkeypress='javascript:JSUtil.numberAllowed(event);' maxlength='10' /> 页 "
						+ " <input type='button' value='GO' class='gobutton' onclick='javascript:"
						+ doSearchFunctionName
						+ "(document.getElementById(\"pageIndexForcreatePage\").value);'/> ";
				pageStr.append(gotoPage);

				return pageStr.toString();
			} else {
				return "第 1 页 /" + space + "共 1 页 /" + space + "共 "
						+ recordTotal + " 条记录";
			}
		} else {
			return "第 1 页 /" + space + "共 1 页 /" + space + "共 " + recordTotal
					+ " 条记录";
		}
	}

	/**
	 * 生成分页链接区间生成优化算法 使用例子： String reStr = createBoundForCutPage(180, 50, 1000);
	 * int lowerLimit = Integer.valueOf(reStr.substring(0, reStr.indexOf("_")));
	 * int upperLimit = Integer.valueOf(reStr.substring(reStr.indexOf("_") + 1,
	 * reStr.length()));
	 * 
	 * 结果 lowerLimit = 155 upperLimit = 205
	 * 
	 * @param currentPage
	 *            当前第几页
	 * @param bound
	 *            区间里最大显示数目
	 * @param totalPage
	 *            总共页数
	 * @return 优化后显示区间
	 * @author AllenZhang
	 */
	private String createBoundForCutPage(int currentPage, int bound,
			int totalPage) {
		int lowerLimit = 0;
		int upperLimit = 0;
		int gap = 0;
		if (currentPage > 0 && bound > 0 && totalPage > 0
				&& totalPage >= currentPage) {
			int boundHalf = bound / 2 + 1;
			if (currentPage < boundHalf) {
				lowerLimit = 1;
				if (totalPage > bound) {
					upperLimit = bound;
				} else {
					upperLimit = totalPage;
				}
			} else if (currentPage > (totalPage - boundHalf)) {
				lowerLimit = totalPage - bound;
				if (lowerLimit <= 0) {
					lowerLimit = 1;
				}
				upperLimit = totalPage;
			} else {
				lowerLimit = currentPage - boundHalf;
				if (lowerLimit <= 0) {
					lowerLimit = 1;
				}
				upperLimit = currentPage + boundHalf;
				if (upperLimit >= totalPage) {
					upperLimit = totalPage;
				}
				gap = upperLimit - lowerLimit;
				if (gap > bound) {
					if (lowerLimit == 1) {
						upperLimit = upperLimit - (gap - bound);
					} else if (upperLimit == totalPage) {
						lowerLimit = lowerLimit + (gap - bound);
					} else {
						lowerLimit = lowerLimit + ((gap - bound) / 2);
						upperLimit = upperLimit - ((gap - bound) / 2);
					}
				} else if (gap < bound) {
					if (lowerLimit == 1) {
						upperLimit = upperLimit + (gap - bound);
					} else if (upperLimit == totalPage) {
						lowerLimit = lowerLimit - (gap - bound);
					} else {
						lowerLimit = lowerLimit - ((gap - bound) / 2);
						upperLimit = upperLimit + ((gap - bound) / 2);
					}
				}
			}
			while (upperLimit - lowerLimit >= bound) {
				lowerLimit++;
			}
		}
		return String.valueOf(lowerLimit) + "_" + String.valueOf(upperLimit);
	}
}